package com.eat.fish_service.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eat.common_utils.IpAndPortUtil;
import com.eat.common_utils.R;
import com.eat.common_utils.ResultCode;
import com.eat.fish_service.entity.Dao.Aquarium;
import com.eat.fish_service.entity.Dao.Fish;
import com.eat.fish_service.entity.Dao.FishEncyclopedia;
import com.eat.fish_service.entity.Dao.FishNum;
import com.eat.fish_service.mapper.FishEncyclopediaMapper;
import com.eat.fish_service.mapper.FishMapper;
import com.eat.fish_service.service.AquariumService;
import com.eat.fish_service.service.FishNumService;
import com.eat.fish_service.service.FishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LWB
 * @since 2022-03-21
 */
@Service
public class FishServiceImpl extends ServiceImpl<FishMapper, Fish> implements FishService {

    @Value("${uploadPath}")
    String uploadPath;

    @Autowired
    AquariumService aquariumService;

    @Autowired
    FishService fishService;

    @Autowired
    FishNumService fishNumService;

    @Override
    public R addFish(Long aquariumId, Fish fish) {
        //判断这个鱼缸的鱼是否满
        Aquarium aquarium = aquariumService.getOne(new QueryWrapper<Aquarium>().eq("id", aquariumId));
        System.out.println(aquarium);
        if (aquarium.getFishNum() == aquarium.getMaxNum()) {
            return R.error().code(ResultCode.FULL).message("添加失败！鱼缸达到最大容量" + "(当前最大容量：" + aquarium.getMaxNum() + ")");
        }

        //判断鱼的名字在次鱼缸中是否重复
        Integer count = baseMapper.selectCount(new QueryWrapper<Fish>().eq("pid", aquariumId).eq("name", fish.getName()));
        if (count > 0) {
            return R.error().code(ResultCode.FISH_NAME_EXISTS).message("名字重复！");
        }

        //鱼表插入鱼
        fish.setPid(aquariumId);
        fish.setFishImg(fish.getFishImg());


        baseMapper.insert(fish);
        //鱼缸表鱼的数量+1
        aquarium.setFishNum(aquarium.getFishNum() + 1);
        aquariumService.updateById(aquarium);

        //鱼数表添加记录
        FishNum fishNum = new FishNum();
        fishNum.setAquariumid(aquariumId);
        fishNum.setFishNum(aquarium.getFishNum());
        fishNumService.getBaseMapper().insert(fishNum);

        return R.ok().data("fishId", fish.getId());
    }


    @Override
    public R addFishPic(MultipartFile pic) {
        if (pic != null) {
            String fileName = System.currentTimeMillis() + pic.getOriginalFilename();

            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录
            File dir = new File(uploadPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            //把浏览器上传的文件复制到希望的位置
            File targetFile = new File(uploadPath, fileName);
            try {
                pic.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
                return R.error().message("上传失败");
            }

            //服务器的ip和端口号
            String ipAndPort = IpAndPortUtil.getIpAndPort();
            String picUrl = "http://"+ipAndPort+"/getPic/"+fileName;

            //返回获取图片的url
            return R.ok().data("picUrl", picUrl);

        } else {
            return R.error().message("上传的文件为空！");
        }

    }


    @Override
    public R editFish(Fish fish) {
        Fish fishFromDB = baseMapper.selectById(fish.getId());
        Fish nameExists = baseMapper.selectOne(new QueryWrapper<Fish>().eq("name", fish.getName()));
        if (nameExists != null && !nameExists.getId().equals(fish.getId()) ) {
            return R.error().code(ResultCode.FISH_NAME_EXISTS).message("该昵称已存在！");
        }

        //stayAge = 现在时间 - 入缸时间
        Long stayAge = new Date().getTime() - fishFromDB.getGmtCreate().getTime();
        //将stayAge转化为月份数
        Integer stayMonths = Integer.valueOf(String.valueOf(stayAge / 1000 / 3600 / 24 / 30));

        //请求发来的InAge为真实年龄，往数据库中插入的是入缸时间
        fish.setInAge(fish.getInAge() - stayMonths);
        int i = baseMapper.updateById(fish);
        if (i == 1) {
            return R.ok();
        } else {
            return R.error().message("修改失败！");
        }
    }

    @Override
    @Transactional(transactionManager = "mainTransMg")
    public R deleteFish(Long aquariumId, String fishId) {
        int result = baseMapper.deleteById(fishId);
        if(result>0){
            Aquarium aquarium = aquariumService.getById(aquariumId);
            aquarium.setFishNum(aquarium.getFishNum()-1);
            aquariumService.updateById(aquarium);

            //鱼数表添加鱼数记录
            FishNum fishNum = new FishNum();
            fishNum.setAquariumid(aquariumId);
            fishNum.setFishNum(aquarium.getFishNum());
            fishNumService.getBaseMapper().insert(fishNum);

            return R.ok();
        }else {
            return R.error().message("删除失败！");
        }

    }

    @Override
    public R uploadFishPic(MultipartFile pic, String fishId) {
//        System.out.println("上传路径为：" + uploadPath);
//        System.out.println("文件名为：" + pic.getOriginalFilename());

        if (pic != null) {
            String fileName = System.currentTimeMillis() + pic.getOriginalFilename();

            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录
            File dir = new File(uploadPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            //把浏览器上传的文件复制到希望的位置
            File targetFile = new File(uploadPath, fileName);
            try {
                pic.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
                return R.error().message("上传失败");
            }

            //服务器的ip和端口号
            String ipAndPort = IpAndPortUtil.getIpAndPort();
            String picUrl = "http://"+ipAndPort+"/getAvater/"+fileName;

            //把图片路径插入到鱼表
            Fish fish = new Fish();
            fish.setId(fishId);
            fish.setFishImg(picUrl);
            fishService.updateById(fish);

            //返回获取图片的url
            return R.ok().data("picUrl", picUrl);

        } else {
            return R.error().message("上传的文件为空！");
        }


    }

    @Override
    public R getAllFish(Long aquariumId) {
        List<Fish> fishList = baseMapper.selectList(new QueryWrapper<Fish>().eq("pid", aquariumId));


        for (Fish item : fishList) {
            Long stayAge = new Date().getTime() - item.getGmtCreate().getTime();
            //返回鱼的当前年龄
//            System.out.println(stayAge);
//            System.out.println(Integer.valueOf(String.valueOf(stayAge/1000/3600/24/30)));
            item.setInAge(item.getInAge() + Integer.valueOf(String.valueOf(stayAge / 1000 / 3600 / 24 / 30)));
//            System.out.println(item.getInAge());
        }
        return R.ok().data("fishList", fishList);
    }

}
